package com.li.controller.listener;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @program: srpingboot-rocketmq
 * @description: 顺序消费 会默认consumeMode = ConsumeMode.CONCURRENTLY(同时接收异步传递的消息)同时多线程消费消息， 无法保持 消息顺序消费
*                  需要使用  consumeMode = ConsumeMode.ORDERLY
 * @author: li
 * @create: 2022-09-25 14:06
 **/
@Component
@RocketMQMessageListener(topic = "TOPIC_TEST_ORDER",
        consumerGroup = "order_product_group_name",
        selectorType = SelectorType.TAG,
        selectorExpression = "tag_order",
        consumeMode = ConsumeMode.ORDERLY)
public class OrderMessageConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
    private static final Logger logger = LoggerFactory.getLogger(OrderMessageConsumer.class);

    @Override
    public void onMessage(MessageExt message) {
        logger.info("OrderMessageConsumer consumer1 收到消息：{}, queueId：{}， threadId：{}, ", new String(message.getBody()), message.getQueueId(), Thread.currentThread());
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.setMaxReconsumeTimes(20);
    }

}
